<template>
    <div>
      <h2>人脸注册</h2>
      <input v-model="phone" placeholder="请输入用户名" />
      <button @click="captureAndRegister">注册</button>
      <!-- 显示视频流 -->
      <video ref="video" autoplay></video>
      <!-- 显示画布 -->
      <canvas ref="canvas"></canvas>
    </div>
  </template>
  
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import http from '../../http';
  
  // 存储用户名
  const phone = ref('');
  // 视频元素引用
  const video = ref<HTMLVideoElement | null>(null);
  // 画布元素引用
  const canvas = ref<HTMLCanvasElement | null>(null);
  
  // 当组件挂载时，初始化摄像头获取视频流
  onMounted(() => {
    initCamera();
  });
  
  // 当组件卸载前，关闭摄像头视频流
  onBeforeUnmount(() => {
    stopCamera();
  });
  
  // 初始化摄像头，获取视频流
  const initCamera = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: true });
      video.value!.srcObject = stream;
      video.value!.play();
    } catch (error) {
      console.error('初始化摄像头出错：', error);
    }
  };
  
  // 停止摄像头视频流
  const stopCamera = () => {
    if (video.value && video.value.srcObject) {
      const tracks = (video.value.srcObject as MediaStream).getTracks();
      tracks.forEach((track) => track.stop());
    }
  };
  
  // 捕获人脸图像并进行注册操作
  const captureAndRegister = async () => {
    try {
      // 等待视频流稳定，可根据实际情况调整等待时间
      await new Promise((resolve) => setTimeout(resolve, 1000));
  
      canvas.value!.width = video.value!.videoWidth;
      canvas.value!.height = video.value!.videoHeight;
      const ctx = canvas.value!.getContext('2d');
      if (ctx) {
        ctx.drawImage(video.value!, 0, 0, canvas.value!.width, canvas.value!.height);
        // 将画布内容转换为Base64编码的图片
        const imageData = canvas.value!.toDataURL('image/jpeg');
        // 显示在页面上的画布
        canvas.value!.style.display = 'block';
  
        const base64Data = imageData.split(',')[1];
        const formdata = new FormData();
        formdata.append('file', base64Data);
        // 调用后端接口上传图片并注册
        const response = await http.post('user/fregister/', formdata);
  
        if (response.data.success) {
          alert('注册成功！');
        } else {
          alert('注册失败：' + response.data.error_msg);
        }
      }
    } catch (error) {
      console.error('人脸注册出错：', error);
    } finally {
      stopCamera();
    }
  };
  </script>
  
  <style>
  /* 可以在这里添加样式来调整视频和画布的大小和位置 */
  video {
    width: 100%;
    height: auto;
  }
  
  canvas {
    width: 100%;
    height: auto;
    border: 1px solid #000; /* 给画布添加边框以便更清晰地看到 */
  }
  </style>
